<template>
  <!--  <div class="charts-container-wrap">-->
  <!--    <div v-if="option.dataset.source.length > 0" class="charts-container" ref="container"></div>-->
  <!--    <div v-else></div>-->
  <!--  </div>-->
  <div class="charts-container" ref="container"></div>
</template>

<script>
import * as echarts from "echarts";
import theme from "../theme/theme.json";
import { mapGetters } from "vuex";

export default {
  name: "BaseChart",
  props: {
    option: {
      type: Object,
      default: () => ({}),
    },
    resize: {
      default: () => "",
    },
    renderer: {
      type: String,
      default: () => "canvas", // canvas缩放时会模糊   svg缩放不会模糊
    },
  },
  data() {
    return {
      instance: null, // echarts实例
    };
  },
  components: {},
  computed: {
    ...mapGetters(["sidebar"]),
  },
  watch: {
    option: {
      handler: function () {
        this.renderECharts();
      },
      deep: true,
    },
    resize: function () {
      this.chartResize();
    },

    "sidebar.opened": {
      handler(val) {
        this.instance.resize();
        setTimeout(() => {
          this.instance.resize();
        }, 0);
      },
    },
  },
  methods: {
    initEChart() {
      this.instance = echarts.init(this.$refs.container, theme, {
        renderer: this.renderer,
      });

      this.instance.on("click", (event) => {
        this.$emit("chartClick", event);
      });
    },
    renderECharts() {
      this.$nextTick(() => {
        if (this.instance) this.instance.clear();
        if (this.option) {
          this.instance.setOption(this.option);
          this.chartResize();
        }
      });
    },
    chartResize() {
      this.$nextTick(() => {
        if (this.instance) this.instance.resize();
      });
    },
  },
  mounted() {
    this.initEChart();
    this.renderECharts();
    let that = this;
    window.addEventListener("resize", () => {
      that.instance.resize();
    });
  },
};
</script>

<style scoped lang="scss">
.charts-container {
  width: 100%;
  height: 100%;
}
</style>
